// pages/screens/add/add.js
const app = getApp();
const regeneratorRuntime = app.globalData.regeneratorRuntime;
var util = require('../../../utils/util.js');
var jsonData = require("../jsondata.js");
const screenservice = require("../../../apiservice/screen/screenservice");
const screenteamservice = require("../../../apiservice/screen/screenteamservice");
const screenitemservice = require("../../../apiservice/screen/screenitemservice");
const screentemplateservice = require("../../../apiservice/screen/screentemplateservice");


Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		new_screenId: "",
		screenType: ["社区筛查", "校园筛查"],
		screenTypeIndex: 0,
		community: ["社区1", "社区2"],
		communityIndex: 0,
		school: [],
		schoolIndex: 0,
		isShowCommunity: "block",
		isShowSchool: "none",

		singleModeIndx: 0,
		singleModeIsChecked: true,

		teamModeIndex: 1,
		teamModeIndexIsChecked: false,

		screenGroup: ["组1", "组2"],
		screenGroupIndex: 0,

		ownerIdName: "Louis",
		ownerId: "xxx",

		screenItem: ["item1", "item2"],
		screenItemIndex: 0,

		screenTemplate: ["template1", "template2"],
		screenTemplateIndex: 0,

		checkscreenResources: [],
		screenResources: jsonData.screenResources,

		dbsChecked: false,
		lxdChecked: false,
		xccChecked: false,
		scChecked: false,
		dxChecked: false,
		scChecked: false,



		dateStartShow: false,
		dateEndShow: false,
		minDate: new Date().getTime(),
		maxDate: util.addDate(new Date().getTime(), "Year", 1),
		startDate: util.formatTime(new Date()),
		endDate: util.formatTime(new Date()),

		systemUserId: "",
		systemUserName: "",
		//选项集
		screenTypeData: jsonData.screenType,
		screenTypeIndex: 0,
		screenTypeName: "社区筛查",

		communityId: null,
		communityName: "请选择",
		schoolId: null,
		schoolName: "请选择",


		screenTeamData: {},
		screenTeamIndex: 0,
		screenTeamName: "请选择",

		screenItemData: {},
		screenItemIndex: 0,
		screenItemName: "请选择",

		screenTemplateData: {},
		screenTemplateIndex: 0,
		screenTemplateName: "请选择",
		checkinAddress: '', //签到地点
		//筛选人信息
		outreachValue: "",
		preachValue: "",
		thedriverValue: "",
		screeningdoctorValue: "",
		screeningnurseValue: "",
		otherValue: "",

		EntryModeIndex: 0,

		SaveDisabled: false,

		screenCrewDisplay: false,
		region: ['湖南省', '长沙市', '天心区'],

    currentStartDate:"",
    currentEndDate:""
	},

  checkRequireAttribute: function () {
    if (this.data.screenTypeIndex == 0) {
      if (this.data.communityName == "请选择") {
        wx.showToast({
          title: '请选择社区',
          icon: 'none'
        })
        return false;
      }
    } else if (this.data.screenTypeIndex == 1) {
      if (this.data.schoolName == "请选择") {
        wx.showToast({
          title: '请选择学校',
          icon: 'none'
        })
        return false;
      }
    }

    if (this.data.screenTeamName == "请选择") {
      wx.showToast({
        title: '请选择筛查小组',
        icon: 'none'
      })
      return false;
    }

    if (this.data.screenTemplateName == "请选择") {
      wx.showToast({
        title: '请选择项目模板',
        icon: 'none'
      })
      return false;
    }
    return true;
  },
	//创建筛查信息
	async UpdateScreenData() {
		//debugger
		try {
      
      

			var that = this.data;
			var screenData = {};
			screenData.new_screenId = this.data.new_screenId;
			screenData.new_checkinaddress = this.data.checkinAddress;
			screenData.new_screentype = that.screenTypeData[that.screenTypeIndex].id;
			if (that.screenTypeIndex == 0) {
				screenData.new_communityId = that.communityId;
			} else if (that.screenTypeIndex == 1) {
				screenData.new_schoolId = that.schoolId;
			}
			//录入模式
			screenData.new_templatetype = jsonData.screenEntryMode[that.EntryModeIndex].id;

			screenData.new_startdate = that.startDate;
			screenData.new_enddate = that.endDate;
			screenData.OwnerId = that.systemUserId;
			if (that.screenTeamData && that.screenTeamData.length > 0) {
				screenData.new_screenteamId = that.screenTeamData[that.screenTeamIndex].new_screenteamId;
			}
			if (that.screenItemData && that.screenItemData.length > 0) {
				screenData.new_new_screenitem = that.screenItemData[that.screenItemIndex].new_screenitemId;
			}
			if (that.screenTemplateData && that.screenTemplateData.length > 0) {
				screenData.new_checkmenu = that.screenTemplateData[that.screenTemplateIndex].templateId;
			}

			screenData.new_outreach = this.data.outreachValue;
			screenData.new_preach = this.data.preachValue;
			screenData.new_thedriver = this.data.thedriverValue;
			screenData.new_screeningdoctor = this.data.screeningdoctorValue;
			screenData.new_screeningnurse = this.data.screeningnurseValue;
			screenData.new_other = this.data.otherValue;

			screenData.Resources = that.checkscreenResources;
			//debugger
			var result = await screenservice.UpdateScreenData(screenData);
			console.log(result);
			if (result.data.resultState == 1) {
				this.JumpPage();
			}
			// 
		} catch (e) {
			console.log(e);
		} finally {
			this.setData({
				SaveDisabled: false,
			});
			wx.hideLoading();
		}
	},



	//筛查类型change时
	changeScreenType: async function(e) {
		console.log(e);
		var index = e.detail.value;
		this.setData({
			screenTypeIndex: index,
			screenTypeName: this.data.screenTypeData[index].name
		});
	},

	//选择社区
	selectCommunity(e) {
		var that = this;
		var url = "../../community/list/list";
		if (this.data.screenTypeIndex == 0) {
			if (that.data.communityId != null) {
				url += "?communityId=" + that.data.communityId;
			}
		}
		wx.navigateTo({
			url: url,
			events: {
				openedCommunityPage: function(e) {
					console.log(e.data)
				},
				communityEvent: function(data) {
					console.log(data)
					that.setData({
						communityId: data.communityId,
						communityName: data.communityName
					});
				}
			},
			success: function(res) {
				res.eventChannel.emit('openedCommunityPage', {
					data: 'choose'
				})
			}
		})
	},

	//选择学校
	// selectSchool(e) {
	// 	var that = this;
	// 	wx.navigateTo({
	// 		url: "../../school/list/list",
	// 		events: {
	// 			openedSchoolPage: function(e) {
	// 				console.log(e.data)
	// 			},
	// 			schoolEvent: function(data) {
	// 				console.log(data)
	// 				that.setData({
	// 					schoolId: data.schoolId,
	// 					schoolName: data.schoolName
	// 				});
	// 			}
	// 		},
	// 		success: function(res) {
	// 			res.eventChannel.emit('openedSchoolPage', {
	// 				data: 'choose'
	// 			})
	// 		}
	// 	})
	// },
	selectSchool(e) {
		var that = this;
		var url = "../../school/list/list";
		wx.navigateTo({
			url: url,
			events: {
				openedSchoolPage: function(e) {
					console.log(e.data)
				},
				schoolEvent: function(data) {
					that.GetSchoolData(that, data.schoolId);

					console.log(data)

					that.setData({
						schoolId: data.schoolId,
						schoolName: data.schoolName
					});
				}
			},
			success: function(res) {
				console.log(that.region);
				res.eventChannel.emit('openedSchoolPage', {
						data: 'choose'
					}),
					res.eventChannel.emit('schoolEvent', {

						data: that.data.region
					})
			}
		})
	},

	async GetSchoolData(that, schoolId) {
		try {
			if (schoolId) {
				var schoolData = await schoolservice.getSchoolDetail(schoolId);
				if (schoolData != null) {
					var provinceName = '';
					var cityName = '';
					var areaName = '';
					if (schoolData.data.new_provinceName != null) {
						provinceName = schoolData.data.new_provinceName;
					}
					if (schoolData.data.new_cityName != null) {
						cityName = schoolData.data.new_cityName;
					}
					if (schoolData.data.new_areaName != null) {
						areaName = schoolData.data.new_areaName;
					}
					that.setData({
						region: [provinceName, cityName, areaName]
					});
				}
				console.log(schoolData.data);
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},
	//显示开始时间
	selectStratDate() {
		this.setData({
			dateStartShow: true
		})
	},

	//关闭开始时间并进行赋值
	onStartConfirm(e) {
		var time = e.detail;
    var enddate = util.getDefaultDate(new Date(time), 17, 0, 0);
		this.setData({
			dateStartShow: false,
			startDate: util.formatTime(new Date(time)),
      currentEndDate: new Date(enddate).getTime(),
      endDate: enddate
		})
	},

	//关闭开始时间
	onStartCancel(e) {
		this.setData({
			dateStartShow: false
		})
	},

	//显示结束时间
	selectEndDate() {
		this.setData({
			dateEndShow: true
		})
	},

	//关闭开始时间并进行赋值
	onEndConfirm(e) {
		var time = e.detail;
		this.setData({
			dateEndShow: false,
			endDate: util.formatTime(new Date(time))
		})
	},

	//关闭结束时间
	onEndCancel(e) {
		this.setData({
			dateEndShow: false
		})
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function(options) {
		let screenresources = await jsonData.initScreenResources();
		//debugger;
		this.setData({
			screenResources: screenresources
		})
		await this.GetScreenTeamData(app.globalData.userInfo.userid);
		await this.GetScreenItemData(app.globalData.userInfo.siteid);
		await this.GetScreenTemplateData();
		if (options.scid) {
			await this.GetScreenData(options.scid);
		}
		//console.log(app.globalData.userInfo);
		this.setData({
			systemUserId: app.globalData.userInfo.userid,
			systemUserName: app.globalData.userInfo.fullname
		});
	},

	//根据当前用户获取到筛查小组
	async GetScreenTeamData(userId) {
		try {
			if (userId) {
				var screenTeamInfo = await screenteamservice.GetScreenTeamByOwnerId(userId);
				console.log(screenTeamInfo.data);
				if (screenTeamInfo) {
					this.setData({
						screenTeamData: screenTeamInfo.data,
					});
				}
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},

	//根据医院获取筛查项目
	async GetScreenItemData(hospitalId) {
		try {
			if (hospitalId) {
				var screenItemInfo = await screenitemservice.GetScreenItemData(hospitalId);
				console.log(screenItemInfo.data);
				if (screenItemInfo) {
					this.setData({
						screenItemData: screenItemInfo.data,
					});
				}
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},

	//获取所有筛查模板
	async GetScreenTemplateData() {
		try {
			var screenTemplateInfo = await screentemplateservice.GetScreenTemplateData();
			console.log(screenTemplateInfo.data);
			if (screenTemplateInfo) {
				this.setData({
					screenTemplateData: screenTemplateInfo.data,
				});
			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},

	//筛查小组change时
	changeScreenTeam: async function(e) {
		console.log(e);
		if (this.data.screenTeamData && this.data.screenTeamData.length > 0) {
			var screenTeamName = this.data.screenTeamData[e.detail.value].new_name;
			this.setData({
				screenTeamIndex: e.detail.value,
				screenTeamName: screenTeamName
			});
		}
	},

	//筛查小组change时
	changeScreenItem: async function(e) {
		console.log(e);
		if (this.data.screenItemData && this.data.screenItemData.length > 0) {
			var screenItemName = this.data.screenItemData[e.detail.value].new_name;
			this.setData({
				screenItemIndex: e.detail.value,
				screenItemName: screenItemName
			});
		}
	},

	//筛查模板change时
	changeScreenTemplate: async function(e) {
		console.log(e);
		if (this.data.screenTemplateData && this.data.screenTemplateData.length > 0) {
			var screenTemplateName = this.data.screenTemplateData[e.detail.value].templateName;
			this.setData({
				screenTemplateIndex: e.detail.value,
				screenTemplateName: screenTemplateName
			});
		}
	},



	//保存并发布
	onSavePublish: async function(e) {
		var currentUserRole = app.globalData.userInfo.mobilerole_systemuser;
		var reg = RegExp(/2/);
		if (reg.exec(currentUserRole)) {
      if (!this.checkRequireAttribute()) return;
      this.setData({
        SaveDisabled: true,
      });
      wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
        title: '加载中',
        icon: 'loading'
      });
			await this.UpdateScreenData();
		}
	},

	JumpPage() {
		wx.switchTab({
			url: "../list/list",
			success: function(e) {
				var page = getCurrentPages().pop();
				if (!page) return;
				page.switchStateScreenCallBack(1);
			}
		});
	},



	//外联改变时 获取值
	ChangeOutreach: function(e) {
		this.setData({
			outreachValue: e.detail
		});
	},

	//宣讲改变时 获取值
	ChangePreach: function(e) {
		this.setData({
			preachValue: e.detail
		});
	},

	//司机改变时 获取值
	ChangeThedriver: function(e) {
		this.setData({
			thedriverValue: e.detail
		});
	},

	//筛查医生改变时 获取值
	ChangeScreeningdoctor: function(e) {
		this.setData({
			screeningdoctorValue: e.detail
		});
	},

	//筛查护士改变时 获取值
	ChangeScreeningnurse: function(e) {
		this.setData({
			screeningnurseValue: e.detail
		});
	},

	//其他改变时 获取值
	ChangeOther: function(e) {
		this.setData({
			otherValue: e.detail
		});
	},





	//录入模式change时
	onEntryModeChange: function(event) {
		// console.log(event);
		// var data=jsonData.screenEntryMode[event.detail.index].id;
		// console.log(data);
		this.setData({
			EntryModeIndex: event.detail.index,
		});
	},


	//筛查资源选中时
	onScreenResourceChange: function(event) {
		this.setData({
			checkscreenResources: event.detail
		});
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	radioChange: function() {},

	screenTypeChange: function(e) {
		var isShowCommunity = "none";
		var isShowSchool = "none";
		if (e.detail.value == 0) {
			isShowCommunity = "block";
			isShowSchool = "none";
		} else {
			isShowCommunity = "none";
			isShowSchool = "block";
		}
		this.setData({
			screenTypeIndex: e.detail.value,
			isShowCommunity: isShowCommunity,
			isShowSchool: isShowSchool
		})
	},
	communityChange: function(e) {
		this.setData({
			communityIndex: e.detail.value,
		})
	},
	schoolChange: function(e) {
		this.setData({
			schoolIndex: e.detail.value,
		})
	},
	screenItemChange: function(e) {
		this.setData({
			screenItemIndex: e.detail.value
		})

	},
	screenTemplateChange: function(e) {
		this.setData({
			screenTemplateIndex: e.detail.value
		})
	},
	screenGroupChange: function(e) {
		this.setData({
			screenGroupIndex: e.detail.value
		})
	},

	dbsChange: function(e) {
		this.setData({
			dbsChecked: !!e.detail.value.length
		});
	},
	lxdChange: function(e) {
		this.setData({
			lxdChecked: !!e.detail.value.length
		});
	},
	xccChange: function(e) {
		this.setData({
			xccChecked: !!e.detail.value.length
		});
	},
	dxChange: function(e) {
		this.setData({
			dxChecked: !!e.detail.value.length
		});
	},
	scChange: function(e) {
		this.setData({
			scChecked: !!e.detail.value.length
		});
	},
	changeDate(e) {
		this.setData({
			date: e.detail.value
		});
	},
	changeTime(e) {
		this.setData({
			time: e.detail.value
		});
	},
	changeDateTime(e) {
		this.setData({
			dateTime: e.detail.value
		});
	},
	changeStartTime(e) {
		this.setData({
			startTime: e.detail.value
		});
	},
	changeEndTime(e) {
		this.setData({
			endTime: e.detail.value
		});
	},
	changeDateTimeColumn(e) {
		var arr = this.data.dateTime,
			dateArr = this.data.dateTimeArray;

		arr[e.detail.column] = e.detail.value;
		dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

		this.setData({
			dateTimeArray: dateArr,
			dateTime: arr
		});
	},
	changeStartTimeColumn(e) {
		var arr = this.data.startTime,
			dateArr = this.data.startTimeArray;

		arr[e.detail.column] = e.detail.value;
		dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

		this.setData({
			startTimeArray: dateArr,
			startTime: arr
		});
	},
	changeEndTimeColumn(e) {
		var arr = this.data.endTime,
			dateArr = this.data.endTimeArray;

		arr[e.detail.column] = e.detail.value;
		dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

		this.setData({
			endTimeArray: dateArr,
			endTime: arr
		});
	},
	screenCrewInfoClick: function(e) {
		this.setData({
			screenCrewDisplay: !this.data.screenCrewDisplay
		})
	},
	//根据screenId获取筛查详细信息
	async GetScreenData(screenId) {
		try {
			if (screenId != null) {
				var screenData = await screenservice.GetScreenByScreenID(screenId);
				console.log(screenData);
				if (screenData) {
					var screenDetail = screenData.data;
					this.assignmentValue(screenDetail);
				}


			}
		} catch (e) {
			console.log(e);
		} finally {
			wx.hideLoading();
		}
	},
	//赋值
	assignmentValue: function(screenDetail) {
		//文本赋值
		this.setData({
			startDate: screenDetail.new_startdate,
			endDate: screenDetail.new_enddate,
			systemUserName: screenDetail.ownerFullName,
			new_screenId: screenDetail.new_screenId,
      currentStartDate:new Date(screenDetail.new_startdate).getTime(),
      currentEndDate: new Date(screenDetail.new_enddate).getTime()
      
		});
		//选项集赋值
		var tmplateindex = this.data.screenTemplateData.findIndex(function(item, index) {
			return item.templateId == screenDetail.new_checkmenu
		})
		var screenItemindex = this.data.screenItemData.findIndex(function(item, index) {
			return item.new_screenitemId == screenDetail.new_new_screenitem
		})
		var screenTeamindex = this.data.screenTeamData.findIndex(function(item, index) {
			return item.new_screenteamId == screenDetail.new_screenteamId
		})

		if (tmplateindex != -1) {
			this.setData({
				screenTemplateIndex: tmplateindex,
				screenTemplateName: screenDetail.new_checkmenuName,
			})
		}

		if (screenTeamindex != -1) {
			this.setData({
				screenTeamIndex: screenTeamindex,
				screenTeamName: screenDetail.new_screenteamName,
			})
		}


		if (screenDetail.new_new_screenitemName) {
			this.setData({
				screenItemName: screenDetail.new_new_screenitemName,
				screenItemIndex: screenItemindex,
			})
		}

		if (screenDetail.new_templatetype == 1) {
			this.setData({
				EntryModeIndex: 1,
			});
		} else if (screenDetail.new_templatetype == 2) {
			this.setData({
				EntryModeIndex: 0,
			});
		}

		if (screenDetail.new_screentype == 100000000) {
			//社区
			this.setData({
				screenTypeIndex: 0,
				screenTypeName: this.data.screenTypeData[0].name
			});
      if (screenDetail.new_communityName!=undefined){
        this.setData({ communityName: screenDetail.new_communityName});
      }
      if (screenDetail.communityId != undefined) {
        this.setData({ communityId: screenDetail.new_communityId });
      }

		} else if (screenDetail.new_screentype == 100000002 || screenDetail.new_screentype == 100000001) {
			//校园
			this.setData({
				screenTypeIndex: 1,
				screenTypeName: this.data.screenTypeData[1].name,
				schoolName: screenDetail.new_schoolName,
				schoolId: screenDetail.new_schoolId,
			});
		}
        
	    //debugger;
		if (screenDetail.equipList != null && screenDetail.equipList.length != 0) {
			var eList = [];
			screenDetail.equipList.forEach(element => {
			
				var checkboxindex = this.data.screenResources.findIndex(function(item, index) {
					return item.name === element.new_name
				})
				eList.push((checkboxindex + 1) + "");

			});
			this.setData({
				checkscreenResources: eList
			})
		}

		//筛查人员信息
		if (screenDetail.new_outreach) {
			this.setData({
				outreachValue: screenDetail.new_outreach,
			})
		}
		if (screenDetail.new_preach) {
			this.setData({
				preachValue: screenDetail.new_preach,
			})
		}
		if (screenDetail.new_thedriver) {
			this.setData({
				thedriverValue: screenDetail.new_thedriver,
			})
		}
		if (screenDetail.new_screeningdoctor) {
			this.setData({
				screeningdoctorValue: screenDetail.new_screeningdoctor,
			})
		}
		if (screenDetail.new_screeningnurse) {
			this.setData({
				screeningnurseValue: screenDetail.new_screeningnurse,
			})
		}
		if (screenDetail.new_other) {
			this.setData({
				otherValue: screenDetail.new_other,
			})
		}
		//签到地点
		if (screenDetail.new_checkinaddress) {
			this.setData({
				checkinAddress: screenDetail.new_checkinaddress,
			})
		}

	}
})
